package com.wangrui.test;

import com.wangrui.dao.UserMapper3;
import com.wangrui.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class MyBatisTest03 {

    /**
     * 获得MyBatis SqlSessionFactory
     * SqlSessionFactory负责创建SqlSession，一旦创建成功，就可以用SqlSession实例来执行映射语句
     * ，commit，rollback，close等方法。
     *
     * @return
     */
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {

            e.printStackTrace();
        }
        return sessionFactory;
    }

    /**
     * sql写在接口上面@Select
     */
    @Test
    public void testSelect() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();
        UserMapper3 userMapper = session.getMapper(UserMapper3.class);
        User user = userMapper.findById("2");
        System.out.println(user.getName());
    }

    @Test
    public void testInsert() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();
        UserMapper3 userMapper = session.getMapper(UserMapper3.class);
        User user = new User("zz", 33);
        System.out.println(userMapper.add(user));
        session.commit();
        session.close();
    }

    @Test
    public void testList() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();
        UserMapper3 userMapper = session.getMapper(UserMapper3.class);
        List<User> userList = userMapper.getAll();
        System.out.println(userList.size());
    }
}
